<template>
    <div class="bring-into-content">
        <div class="bring-into-header-btn" v-if="getTrialStatus == '1'">

            <!-- <el-button type="primary" plain :icon="Grid" @click="handleBringIntoMenu(1)"
        >唯一二维码</el-button
      >
      <el-button type="primary" plain :icon="Setting" @click="handleBringIntoMenu(2)"
        >配置信息</el-button
      >
      <el-button type="primary" plain :icon="Plus" @click="handleBringIntoMenu(3)"
        >高级配置</el-button
      >
      <el-button type="primary" plain :icon="Operation" @click="handleBringIntoMenu(4)"
        >自动编号</el-button
      >
      <el-button type="primary" plain :icon="DocumentChecked" @click="handleBringIntoMenu(5)"
        >导入数据</el-button
      >-->
      <el-button type="primary" plain :icon="DocumentChecked" @click="handleBringIntoMenu(6)"
        >导入病例</el-button
      >
        </div>
        <avue-crud :option="bringIntoOption" v-model:search="search" v-model:page="page" v-model="bringIntoForm"
            :table-loading="loading" :data="data" :before-open="beforeOpen" ref="crud" @row-update="rowUpdate"
            @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @on-load="onLoad">

            <template #menu-left>
                <el-button type="primary" plain :icon="Plus" @click="handleBringIntoMenu(0)">新建病例</el-button>
            </template>

            <template #menu="{ row, index }">
                <el-button type="primary" plain size="small"
                    @click="handleBringIntoMenu(9, row, index)">入组采集</el-button>
            </template>
            <template #createUser="{ row, index }">
                <span style="color: #3c8dbc; cursor: pointer" @click="handleBringIntoMenu(7, row, index)">{{
                    row.createUser
                    }}</span>
            </template>
            <template #CRF="{ row }">
                <el-button type="primary" plain size="small" :icon="Search" @click="handleBringIntoMenu(8, row)">查
                    看</el-button>
            </template>
            <template #name-header="{ column }">
                <el-tooltip class="box-item" effect="dark" :content="!isCutName ? '切换成全名' : '切换成姓名缩写'" placement="top">
                    <span style="color: #409eff;cursor: pointer" @click="cutName">姓名(切换)</span>
                </el-tooltip>
            </template>

            <template #name="{ row }">
                <span style="color: #409eff;">{{ !isCutName ? row.name : row.nameSx }}</span>
            </template>
        </avue-crud>
        <el-dialog v-model="isBringIntoDialog" :title="bringIntoDialogTitle" :width="bringIntoDialogWidth">
            <bringIntoAdd v-if="bringIntoMenuType === 0" @changeAddNewCase="changeAddNewCase" :selectTab="4" />
            <!-- @submit="allocationDialogSubmit" -->
            <!-- <avue-form :option="allocationDialogOption" v-model="allocationDialogForm"></avue-form> -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="isBringIntoDialog = false">关 闭</el-button>
                    <!-- <el-button type="primary" @click="dialogVisible = false"> 确 定 </el-button> -->
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { getList, getDetail, add, update, remove, npCrf } from '@/api/clinicalcase/clinicalCase';
import { getTrialDetail } from '@/api/trial/trial';
import { Plus, Grid, Setting, Operation, DocumentChecked, Search } from '@element-plus/icons-vue';
import bringIntos from '@/option/bringInto/bringInto';
import bringIntoAdd from './bringIntoMenu/bringIntoAdd.vue';
import { ref, reactive, computed, onMounted, defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
const crud = ref();
const route = useRoute();
const emit = defineEmits();
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const store = useStore();
const bringIntoOption = ref(bringIntos);
const bringIntoForm = ref({});
const data = ref([]);
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
    pageSize: 10,
    currentPage: 1,
    total: 0,
});
const selectionList = ref([]);
let bringIntoMenuType = ref(null);
let isBringIntoDialog = ref(false);
let bringIntoDialogTitle = ref('');
let bringIntoDialogWidth = ref(500);

let getTrialStatus = ref('2');
let sendAddNewCaseObj = ref({});

/*
  type 0:新建病例
  type 1:唯一二维码
  type 2:配置信息
  type 3:高级配置
  type 4:自动编号
  type 5:导入数据
  type 6:导入病例
  type 7:姓名点击
  type 8:CRF查看点击
  type 9:入组采集
*/
const handleBringIntoMenu = (type, row = {}, index = null) => {
    bringIntoMenuType.value = type;
    const actions = {
        0: () => {
            isBringIntoDialog.value = true;
            bringIntoDialogTitle.value = '新建病例';
        },
        7: () => {
            crud.value.rowEdit(row, index);
        },
        8: () => {
            router.push({
                path: '/trial/gather',
                query: {
                    selectTab: 4,
                    trialId: routerQuery.value.trialId,
                    groupId: row.groupId,
                    clinicalCaseId: row.id,
                    clinicalCaseType: type,
                },
            });
        },
        9: () => {
            router.push({
                path: '/trial/gather',
                query: {
                    selectTab: 4,
                    trialId: routerQuery.value.trialId,
                    groupId: row.groupId,
                    clinicalCaseId: row.id,
                    clinicalCaseType: type,
                },
            });
        },
    };

    // 执行对应的操作
    if (actions[type]) actions[type]();
};
let isCutName = ref(false);
// 姓名切换
const cutName = () => {
    isCutName.value = !isCutName.value;
}
// 新建病例，子页面点击“添加新病例”按钮，返回方法
const changeAddNewCase = (groupId) => {
    sendAddNewCaseObj.value = { groupId };
    crud.value.rowAdd();
    isBringIntoDialog.value = false;
};
const initTrialDetail = id => {
    if (id) {
        getTrialDetail(id).then(res => {
            getTrialStatus.value = res.data.data.status;
        });
    }
};

onMounted(() => {
    initOptions();
    getTrialStatus.value = '2';
    initTrialDetail(routerQuery.value.trialId);
});
const initOptions = () => {
    bringIntoOption.value.delBtn = getTrialStatus.value == '1' ? true : false;
    bringIntoOption.value.editBtn = getTrialStatus.value == '1' ? true : false;
};

const rowSave = (row, done, loading) => {
    delete row.timeLists;
    delete row.birthdays;
    row.trial = routerQuery.value.trialId;
    row.groupId = sendAddNewCaseObj.value.groupId || '';
    add(row)
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
            done();
        })
        .catch(error => {
            loading();
            window.console.console.log(error);
        });
};
const rowUpdate = (row, index, done, loading) => {
    delete row.timeLists;
    delete row.birthdays;
    update(row).then(
        () => {
            // onLoad(page.value);
            TabRefreshChange();
            ElMessage({
                type: 'success',
                message: '操作成功!',
            });
            done();
        },
        error => {
            loading();
            console.log(error);
        }
    );
};
const rowDel = row => {
    ElMessageBox.confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(row.id);
        })
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
        });
};

const handleDelete = () => {
    if (selectionList.value.length === 0) {
        ElMessage.warning('请选择至少一条数据');
        return;
    }
    ElMessageBox.confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(ids.value);
        })
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
        });
};
const searchReset = () => {
    query.value = {};
    TabRefreshChange();
    // onLoad(page.value, query.value);
};
const searchChange = (params, done) => {
    if (params.birthdays instanceof Array) {
        params.birthday = params.birthdays.join(',');
        delete params.birthdays;
    }
    if (params.timeLists instanceof Array) {
        params.timeLists = params.timeLists.join(',');
    }
    console.log(params);
    query.value = params;
    page.value.currentPage = 1;
    TabRefreshChange();
    // onLoad(page.value, params);
    done();
};
const beforeOpen = (done, type) => {
    if (['edit', 'view'].includes(type)) {
        getDetail(bringIntoForm.value.id).then(res => {
            bringIntoForm.value = res.data.data;
        });
    }
    done();
};
const selectionChange = list => {
    selectionList.value = list;
};
const selectionClear = () => {
    selectionList.value = [];
    crud.value.toggleSelection();
};
const currentChange = currentPage => {
    page.value.currentPage = currentPage;
    TabRefreshChange();
};
const sizeChange = pageSize => {
    page.value.pageSize = pageSize;
    TabRefreshChange();
};
const refreshChange = () => {
    onLoad(page.value, query.value);
};
const TabRefreshChange = () => {
    // if (selectTab.value === 1) {
    //   query.value.publicShare = '1';
    // } else if (selectTab.value === 2) {
    //   query.value.deptShare = '1';
    // }
    // if (selectTab.value === 3) {
    //   query.value.create_user = userInfo.value.user_id;
    // }
    onLoad(page.value, query.value);
};
const onLoad = (page, params = {}) => {
    loading.value = true;

    const { name, lbType } = query.value;

    let values = {
        name_: name,
        lbType_: lbType,
        descs: 'create_time',
        trial: routerQuery.value.trialId,
        ...params,
    };

    getList(page.currentPage, page.pageSize, values).then(res => {
        const DATA = res.data.data;
        page.total = DATA.total;
        data.value = DATA.records;
        data.value.forEach(item => {
            item.isShareSelect = 3;
            if (item.publicShare == '1') {
                item.isShareBtn = '0';
                item.isShareSelect = 1;
            } else if (item.deptShare == '1') {
                item.isShareBtn = '6';
                item.isShareSelect = 2;
            }
        });
        loading.value = false;
        selectionClear();
    });
};
</script>
<style scoped>
.bring-into-content {
    width: 90%;
    height: 100%;
}

.bring-into-header-btn {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
}
</style>
